﻿Imports AugmentLib.Database
Imports System.Configuration.ConfigurationManager
Imports AugmentLib.InputOutput.Encryption
Imports System.Net

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable

        Try
            objDB.OpenConnection()
            objDB.dbVariable.SQLString = "SELECT CompanyName FROM AW_Setting"
            objDB.FillData(TempDT, "Setting", Database.SQLCommandType.NormalString)
            objDB.CloseConnection()
        Catch ex As Exception

        Finally
            If (objDB IsNot Nothing) Then
                objDB.CloseConnection()
            End If
        End Try

        lblTitle.Text = TempDT.Rows(0).Item("CompanyName").ToString
        Session.Add("TT", TempDT.Rows(0).Item("CompanyName").ToString)
        txtName.Focus()

    End Sub

    Protected Sub cmdLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
        Session.Clear()

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable
        Try
            objDB.OpenConnection()

            '***** Location Check **********/
            Dim latitude, longitude As String
            latitude = lblLat.Text
            longitude = lblLng.Text

            Dim mylat As Double, mylng As Double

            mylat = FormatNumber(CDbl(latitude), 5)
            mylng = FormatNumber(CDbl(longitude), 5)

            '***** Get Header ***********
            Dim tokenReturn As String
            tokenReturn = Request.Headers("httphead")
            '****************************

            objDB.dbVariable.SQLString = "SELECT ValidLatitude, ValidLongitude,AddedSecurity, AddedPassword FROM AW_ValidHost WHERE (ValidLatitude BETWEEN @lat-0.0001 AND @lat+0.0001) AND (ValidLongitude BETWEEN @lng-0.0001 AND @lng+0.0001)"
            objDB.AddParameter("lat", Data.SqlDbType.Float, mylat)
            objDB.AddParameter("lng", Data.SqlDbType.Float, mylng)
            objDB.FillData(TempDT, "Setting", Database.SQLCommandType.NormalString)

            If TempDT.Rows.Count > 0 Then
                If 1 > 0 Then
                End If
                objDB.CloseConnection()
                Dim AddedSecurity As String = ""
                Dim AddedPassword As String = ""

                For Each ReadRow As Data.DataRow In TempDT.Rows
                    AddedSecurity = ReadRow.Item("AddedSecurity").ToString
                    AddedPassword = ReadRow.Item("AddedPassword").ToString
                Next

                If AddedSecurity <> "" And AddedSecurity.Equals("1") Then
                    If tokenReturn <> AddedPassword Then
                        lblMsgError.Text = "Fail added security check. Please contact administrator to request access!"
                    End If
                End If
                Response.Write("Valid Location=" + latitude.ToString + "," + longitude.ToString)
            Else
                objDB.dbVariable.SQLString = "insert into AW_InvalidHost (InvalidLatitude, InvalidLongitude) values (@inlat,@inlng);"

                objDB.AddParameter("inlat", Data.SqlDbType.Float, mylat)
                objDB.AddParameter("inlng", Data.SqlDbType.Float, mylng)
                objDB.ExecuteQuery()
                objDB.CloseConnection()
                Response.Write("Invalid Location=" + mylat.ToString + "," + mylng.ToString)
                lblMsgError.Text = "Invalid location. Please contact administrator to request access!"
            End If
            '********** Location Check End **************

            TempDT = New Data.DataTable
            objDB.OpenConnection()

            objDB.dbVariable.SQLString = "Select StaffId, Initial, UserName, Password, StaffType, Name, SR, SC, SL, SI, " & _
                                        "RR, RC, RL, RI, Avatar, Phone, Mobile, Fax, Email FROM AW_Staff " & _
                                        "WHERE UserName=@UserName AND Password=@Password AND StatusDelete = 0"
            objDB.AddParameter("UserName", Data.SqlDbType.NVarChar, txtName.Text.Trim.ToUpper)
            objDB.AddParameter("Password", Data.SqlDbType.NVarChar, SymmetricEncrypt(txtPassword.Text.Trim.Substring(0, txtPassword.Text.Length - 5), "augment"))

            objDB.FillData(TempDT, "AW_Staff", Database.SQLCommandType.NormalString)

            objDB.dbVariable.SQLString = "insert into AW_Login (LoginName,LoginStatus) values(@LoginName,@LoginStatus);"
            objDB.AddParameter("LoginName", Data.SqlDbType.VarChar, txtName.Text)

            If TempDT.Rows.Count > 0 Then
                objDB.AddParameter("LoginStatus", Data.SqlDbType.Bit, True)
                objDB.ExecuteQuery()
                objDB.CloseConnection()

                Me.Session.Add("StaffId", TempDT.Rows(0).Item("StaffId").ToString)
                Me.Session.Add("StaffType", TempDT.Rows(0).Item("StaffType").ToString)
                Me.Session.Add("UserName", txtName.Text.Trim)
                Response.Redirect("Dashboard.aspx")
            Else
                objDB.AddParameter("LoginStatus", Data.SqlDbType.Bit, False)
                objDB.ExecuteQuery()
                objDB.CloseConnection()

                lblMsgError.Text = "Invalid username or password. Please try again!"
            End If
        Catch ex As Exception

        Finally
            If (objDB IsNot Nothing) Then
                objDB.CloseConnection()
            End If
        End Try
    End Sub

    Public Shared Function GetIPAddress() As String
        Dim context As System.Web.HttpContext = System.Web.HttpContext.Current
        Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
        If String.IsNullOrEmpty(sIPAddress) Then
            Return context.Request.ServerVariables("REMOTE_ADDR")
        Else
            Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c})
            Return ipArray(0)
        End If
    End Function
End Class
